package cassandrawindow;

import count.FraudCountByGuid;
import count.FraudGuidInSecRangeResult;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.log4j.xml.DOMConfigurator;
import util.ConfigUtil;

public class HandleFraudClick {    
    public static final String KEYSPACE                             =   "AdsData";
    public static final String ColumFamly                           =   "BannerViewCountCf";
    public static final String ColumFamlyBannerClickCountCf         =   "BannerClickCountCf";
    public static final String ColumFamlyBannerViewCountCf          =   "BannerViewCountCf";

    public static final String ColumFamlyCampaignClickCountCf       =   "CampaignCountCf";
    public static final String ColumFamlyCampaignViewCountCf        =   "CampaignViewCountCf";

    public static final String ColumFamlyCampaignIPCountCf          =   "CampaignIpCountCf";
    public static final String SuperColumFamlyCampaignGuidClick     =   "Guid_Click_Super_Cf";    
    public static final String FRAUDCLICKKEYSPACE                   =   "FraudKs";
    
    public static long checkFraudClick   =   0;
     
    public void handleData() throws ParseException, InterruptedException, IOException
    {
        long first_time = System.currentTimeMillis();
        try {
            CassandraAction cassAct = new CassandraAction(ACCOUNT.CLUSTERNAME ,ACCOUNT.URL, ACCOUNT.PORT);
            cassAct.initReadWirte(FRAUDCLICKKEYSPACE);
            //MysqlDataManager mysql = new MysqlDataManager();            
            //ConfigUtil.setPathConfig("E:\\config_fraud_click\\conf.properties");
            //DOMConfigurator.configure("E:\\config_fraud_click\\log4j.xml");
            ConfigUtil.setPathConfig("/home/bigdata/livebudget/schedulerFraudClick/properties/conf.properties");
            //DOMConfigurator.configure("/home/bigdata/schedulerFraudClick/properties/log4j.xml");
            //DOMConfigurator.configure("/home/bigdata/schedulerFraudClick/properties/log4j.xml");
            //String currentDate = TimeUtil.getCurrentTimeInString();//2012-07-24
            //String currentDate = handleDate();//2012-07-24
            String currentDate = CONSTANT.Date;
            String[] arrTime = new String[3];
            arrTime = currentDate.split("-");
            /*
             *chay fraudclick tu 6h sang->5h59 sang ngay hom sau
             */
            Calendar startCalendar = Calendar.getInstance();
            //startCalendar.set(2012, 06, 07, 0, 0, 00);
            startCalendar.set(Integer.valueOf(arrTime[0]), Integer.valueOf(arrTime[1])-1, Integer.valueOf(arrTime[2]), 6, 0, 00);
            startCalendar.set(Calendar.MILLISECOND, 0);                        
            long timeInMillis = startCalendar.getTimeInMillis();           
            // end time
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.set(Integer.valueOf(arrTime[0]), Integer.valueOf(arrTime[1])-1, Integer.valueOf(arrTime[2]) +1 , 5, 59, 00);
            endCalendar.set(Calendar.MILLISECOND, 0);
            long endCalendarTime = endCalendar.getTimeInMillis();            
             /*
            long timeInMillis = TimeUtil.getCurrentTime()*1000 - 13*60*60*1000;// cách thời điểm hienj tại một 1h
            long endCalendarTime = TimeUtil.getCurrentTime()*1000; //thoi diem hien tai
            */
            List<FraudGuidInSecRangeResult> fraudGuidInSecRangeResults = new FraudCountByGuid().countFraudGuidInSecSlice(10L, timeInMillis, endCalendarTime);
            Debug.println("so guideid khong hop le theo giay:" +fraudGuidInSecRangeResults.size());
            Iterator it = fraudGuidInSecRangeResults.iterator();
            StringBuilder sbff = new StringBuilder();
            //String insertDate = "2012-07-07";            
            while(it.hasNext())
            {
                FraudGuidInSecRangeResult value = (FraudGuidInSecRangeResult) it.next();                
                //System.out.println("tong so click:" +value.getTotalClick());
                //System.out.println("guidid:" +value.getGuid());
                //System.out.println("timestamp:" +value.getTimeStamp());                
                String str = cassAct.getFraudClick(value.getGuid(), value.getTimeStamp(), SuperColumFamlyCampaignGuidClick, currentDate);
                sbff.append(str);
                //check null
                if(sbff.toString().length() > 10000)
                {
                     MysqlDataManager mysql = new MysqlDataManager();
                    //xu li cho du lieu cuoi
                    String relStr = sbff.toString();
                    String valInsert = relStr.substring(0, (relStr.length()-1));                    
                    mysql.insertFraudClick(valInsert);
                    sbff.setLength(0);
                }               
            }
            
            if(sbff.toString().length() > 1)
            {
                 MysqlDataManager mysql = new MysqlDataManager();
                //xu li cho du lieu cuoi
                String relStr = sbff.toString();
                String valInsert = relStr.substring(0, (relStr.length()-1));
                mysql.insertFraudClick(valInsert);
                sbff.setLength(0);
            }

        } catch (Exception ex)
        {
            System.out.println("exception rule 1(tinh fraud click theo giay):"+ex.getMessage());
        }
        long last_time = System.currentTimeMillis();
        Debug.println("Thoi gian chay  :" +(last_time-first_time));
        Debug.println("sucess rule 1");
    }

    /*
     * Lay thoi gian tu 6h sang ngay hom truoc toi 5h59 sang ngay hom sau
     * Coi la 1 ngay
     */
    public String handleDate()
    {
        String retDate = "";//2012-07-24
        String date = TimeUtil.getCurrentTimeInStringForLog();//yyyy/MM/dd H:mm:ss

        String[] arrTime = new String[2];
        String[] firstArrTime = new String[3];
        String[] secondArrTime = new String[3];

        arrTime = date.split(" ");
        firstArrTime    = arrTime[1].split(":");
        secondArrTime   = arrTime[0].split("-");
        //init checkDate neu khoi dong service from 0h -> 6h
        if(checkFraudClick == 0)
        {
            checkFraudClick = TimeUtil.getCurrentTime();
        }
        
        if(Integer.valueOf(firstArrTime[0]) >= 6 && Integer.valueOf(firstArrTime[0]) <= 23)
        {
            checkFraudClick = TimeUtil.getCurrentTime();
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+secondArrTime[2];
        } else if (Integer.valueOf(firstArrTime[0]) >= 0 && Integer.valueOf(firstArrTime[0]) < 6 && TimeUtil.getCurrentTime() >= checkFraudClick)
        {
            Debug.println(date + "_" + TimeUtil.getCurrentTime() + "_" + checkFraudClick);
            int day = Integer.valueOf(secondArrTime[2]) - 1;
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+String.valueOf(day);
        }        
        return retDate;
    }
}
